<?php

class Nimblecms_Form_Decorator_Yandexmap extends Zend_Form_Decorator_Abstract {

	private function _getJs($id_field) {
		$html = '<script type="text/javascript">
					var map;
					window.onload = function () {
						map = new YMaps.Map(document.getElementById("YMapsID"));
						map.setCenter(new YMaps.GeoPoint(60.583333343333, 56.833333343333), 12);
						geoPlacemark = new YMaps.Placemark(new YMaps.GeoPoint(60.583333343333, 56.833333343333), { draggable: 1 });
						map.addControl(new YMaps.SmallZoom());
						map.addOverlay(geoPlacemark);
						YMaps.Events.observe(geoPlacemark, geoPlacemark.Events.Drag, function (obj) {
    						document.getElementById("' . $id_field . '").value = obj.getGeoPoint();
 						 });
					}
					function showAddress() {
					var address = document.getElementById("YMapsAddress").value;
					  var geocoder = new YMaps.Geocoder(address, { results: 1, boundedBy: map.getBounds() });
					  YMaps.Events.observe(geocoder, geocoder.Events.Load, function (obj) {
					    if (this.length()) {
					      geoCoords = obj.get(0).getGeoPoint();
					      geoPlacemark.setGeoPoint(geoCoords);
					      map.panTo(geoCoords)
					      document.getElementById("' . $id_field . '").value = geoCoords;
					    } else {
					      alert("Not Found");
					    }
					  });
					  YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (geocoder, error) {
					    alert("Error: " + error);
					  })
					}
				</script>';
		$html .= '<input size="40" type="text" name="YMapsAdress" value="" id="YMapsAddress" /><input type="button" name="YMapsSearchButton" value="Search" onclick="showAddress();" />';
		$html .= '<div id="YMapsID" style="width:400px;height:320px;margin-bottom: 20px;"></div>';
		return $html;
	}
	
	public function render($content) {
		$element = $this->getElement();
		if(!$element instanceof Zend_Form_Element) {
			return $content;
		}
		
		if (null === $element->getView ()) {
			return $content;
		}
		
		$placement = $this->getPlacement ();
		
		$separator = $this->getSeparator ();
		
		$id_element = $element->getAttrib('id');
		if($id_element == '') return null;
		
		switch ($placement) {
			
			case 'APPEND' :
				return $content . $separator . $this->_getJs($id_element);
			
			case 'PREPEND' :
				return $content . $separator . $this->_getJs($id_element);
			case null :
			
			default :
				return $content . $separator . $this->_getJs($id_element);
		}
	}
}